

const { exec } = require('../db/mysql')
const { SuccessModel, ErrorModel } = require('../model/resModel')

/* 
author:作者
keyword：关键词
*/

// 获取博客列表
/* 
1=1:因为下面有判断语句，不写1=1会发生拼接报错，
select * from blogs where 1=1 + `order by createtime desc`
因为author和keyword的值不确定有没有
*/
const getList = (author, keyword) => {
    let sql = `select * from blogs where 1=1 `
    if (author) {
        sql += `and author='${ author }' `
    }
    if (keyword) {
        sql += `and title like '%${ keyword }%' `
    }
    sql += `order by createtime desc`

  
    return exec(sql)
}

// 获取博客详情
const getDetail = (id) => {
    const sql = `select * from blogs where id='${ id }'`
    return exec(sql).then(rows => {
        // 把数组变成对象的格式
        return rows[0]
    })
}

// 新建博客
const newBlog = (blogData = {}) => {
    const title = blogData.title;
    const author = blogData.author
    const content = blogData.content
    const createtime = Date.now()

    const sql = `insert into blogs (title, content, createtime,author) value('${ title }','${ content }','${ createtime }','${ author }')`
    return exec(sql).then(insertData => {
        return {
            id: insertData.insertId
        }
    })
}

// 更新博客
/* 
id是更新的博客的id 
blogData是一个博客对象 包含title content 
*/
const updateBlog = (id, blogData = {}) => {
    const title = blogData.title
    const content = blogData.content
    const sql = `update blogs set title='${ title }',content='${ content }' where id='${ id }'`
    return exec(sql).then(updateData => {
        if (updateData.affectedRows > 0) {
            return true
        }
        return false // true是成功 false是失败
    })
}

// 删除博客
const delBlog = (id, author) => {
    const sql = `delete from blogs where id='${ id }' and author='${ author }'`

    return exec(sql).then(deleteData => {
        if (deleteData.affectedRows > 0) {
            return true
        }
        return false
    })
}


module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    delBlog
}
